var path = require('path');
var fs = require('fs');

var db=require('../utils/db');
var tools=require('../utils/tools');
var user_map=require('../utils/userMap');
var checkCode_map=require('../utils/checkCodeMap');

exports.use_func=function(res,json){
    var account=json.useracc;
    var password=json.userpwd;
    var daili_id=json.sid;
    var realname=json.username;
    var nickname=json.useracc;
    var score=0;
    if(json.score){
        score=json.score;
    }

    db.is_account_exist(account,function(status){
        var info={};
        info.status=status;
        switch(status){
            case 0:
            info.info='账号不能为空';
            break;
            case 1:
            info.info='账号出错啦';
            break;
            case 2:
            info.info='账号已经存在';
            break;
        }
        if(status!=3){
            tools.send(res,info);
        }else{
            db.create_account(account,password,daili_id,realname,nickname,null,score,function(arg){
                if(arg){
                    tools.send(res,{status:1,info:'注册成功'});
                }else{
                    tools.send(res,{status:-1,info:'注册失败'});
                }
            });
        }
    });
};

exports.checkCode_func=function(res,query){
    // console.log(query);
    if(query.ackey){
        var code = checkCode_map.get_map(query.ackey);
        if(code){
            other_req(res,code.code);
        }
    }
};

function get_file_content(filepath,callback) {
    return fs.readFile(filepath,callback);
}

function other_req(res,pathname){
    var dirname=path.join(__dirname, '..\\codes',pathname+'.png');
    get_file_content(dirname,function(err,data){
        if(err){
            res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
            res.write(data);
            res.end();
        }else{
            res.writeHead(200,{"Content-Type":"image/png;charset='utf-8'"});
            res.write(data);
            res.end();
        }
    });
};

exports.online_func=function(res,query){
    if(query.key){
        if( user_map.is_key_exist(query.key)){
            var info = user_map.get_user(query.key);
            // console.log(info);
            db.get_user_info(info.account,function(flag,_info){
                if(flag){
                    info.info=_info;
                    user_map.add_userMap(info.account,query.key,info.ackey,_info);
                    tools.send(res,{status:1,info:'登录成功',score:info.info.score,usname:info.info.nickname,online:{onlineUser:user_map.return_size()}});
                }else{
                    tools.send(res,{status:-1,info:'连接已失效，请重新登录'});
                }
            });
            
        }else{
            tools.send(res,{status:-1,info:'连接已失效，请重新登录'});
        }
        
    }else{//获取ackey
        var ackey =tools.generateMixed(11);
        var code =tools.getCode(checkCode_map.return_codes());
        checkCode_map.add_map(ackey,code,new Date().Format('yyyy-MM-dd hh:mm:ss'));
        tools.send(res,{status:1,ackey:ackey});
    }
};

exports.login_func=function(res,json,query){
    if(query.ackey){
        var code=checkCode_map.get_map(query.ackey);
        if(code){
            if(code.code==query.checkcode){
                db.login_account(json.name,json.pwd,function(arg){
                    if(arg){
                        db.get_user_info(json.name,function(flag,info){
                            if(flag){
                                checkCode_map.delete_map(query.ackey);
                                var key=tools.generateMixed(11);
                                user_map.add_userMap(json.name,key,query.ackey,info);
                                db.update_user_lasttime(info.account,new Date().Format('yyyy-MM-dd hh:mm:ss'),null);
                                tools.send(res,{status:1,info:'登录成功',key:key,score:info.score,userrealname:info.realname,lastlogintime:info.lasttime,nickname:info.nickname});
                            }else{
                                tools.send(res,{status:-1,info:'登录失败'});
                            }
                        });
                        
                    }else{
                        tools.send(res,{status:-1,info:'账号或密码错误'});
                    }
                });
            }else{
                tools.send(res,{status:-1,info:'验证码不正确'});
            }
        }else{
            tools.send(res,{status:-1,info:'验证码已失效'});
        }
    }else{
        tools.send(res,{status:-1,info:'登录验证失败'});
    }
};
//公告
exports.GetPublic_func=function(res,json){
    // console.log(json);
    db.get_notices_public(function(flag,arg){
        if(flag){
            var info=[];
            for(var i=0;i<arg.length;i++){
                let temp=arg[i];
                temp.addtime=new Date(temp.addtime).Format('yyyy-MM-dd hh:mm:ss');
                info.push(temp);
            }
            tools.send(res,{status:1,data:info});
        }else{
            tools.send(res,{status:-1,data:[]});
        }
    });
};
//游戏列表
exports.GetGameList_func=function(res,json){
    // console.log(json);
    var info ={};
    db.get_gamegroup_list(function(flag,arg){
        if(flag){
            info.types=arg;
            db.get_game_list(function(flag,arg){
                if(flag){
                    info.infos={};
                    var typeid=0;
                    var temp_list=[];
                    for(var i=0;i<arg.length;i++){
                        if(typeid==0){
                            typeid=arg[i].typeid;
                        }
                        if(typeid!=arg[i].typeid){
                            info.infos[typeid]=temp_list;
                            temp_list=[];
                            typeid=arg[i].typeid;
                            temp_list.push(arg[i]);
                        }else{
                            temp_list.push(arg[i]);
                        }
                    }
                    info.infos[typeid]=temp_list;
                    tools.send(res,info);
                }else{
                    tools.send(res,{status:-1});
                }
            });
        }else{
            tools.send(res,{status:-1});
        }
    });
};
//游戏推荐
exports.GetEnjoyGames_func=function(res,json){
    // console.log(json);
    var info={};
    info.lastgame=[];
    info.lovegame=[];
    info.recommend=[];
    var user=user_map.get_user(json.key);
    if(user!==null){
        db.get_user_info(user.account,function(flag,arg){
            if(flag){
                user.info=arg;
                info.lovegame=JSON.parse(user.info.lovegame).games;
                info.lastgame=JSON.parse(user.info.lastgame).games;
            }
            db.get_games_recommend(function(flag,arg){
                if(flag){
                    for(var i=0;i<arg.length;i++){
                        info.recommend.push(arg[i].id);
                    }
                }
                tools.send(res,{status:1,lastgame: info.lastgame,lovegame: info.lovegame,recommend: info.recommend});
            });
        });
    }
};

exports.UseSaveLoveGames_func=function(res,json,query){
    var user=user_map.get_user(query.key);
    if(user!==null){
        db.update_UseSaveLoveGames(user.account,JSON.stringify({games:json.lovegame}),function(flag){
            if(flag){
                tools.send(res,{status:1,info:'游戏添加成功'});
            }else{
                tools.send(res,{status:-1,info:'游戏添加失败'});
            }
        }.bind(this));
    }else{
        tools.send(res,{status:-1,info:'游戏添加失败'});
    }
};
